package com.fucking.great.context.exception;

import cn.hutool.json.JSONObject;

public class TxnRuntimeException  extends RuntimeException{
    private final String errorCode;
    private final Throwable throwable;
    public TxnRuntimeException(String errorCode,String message) {
        super(message);
        this.errorCode = errorCode;
        this.throwable = this;
    }
    public TxnRuntimeException(String errorCode,Throwable cause) {
        super(cause.getMessage(), cause);
        this.errorCode = errorCode;
        this.throwable = cause;
    }

    public TxnRuntimeException(String errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
        this.throwable = cause;
    }

    /**
     * 抛异常,异常转态码/信息,自定义
     * @see TxnRuntimeException#TxnRuntimeException(java.lang.String, java.lang.String, java.lang.Throwable)
     * @param errorCode
     * @param message
     * @param cause
     */
    public static void throwException(String errorCode,String message, Throwable cause){
        throw new TxnRuntimeException(errorCode,message,cause);
    }
    /**
     * 异常信息从cause中获得.
     * @param errorCode
     * @param cause
     */
    public static void throwException(String errorCode, Throwable cause){
        throw new TxnRuntimeException(errorCode,cause.getMessage(),cause);
    }
    /**
     * 抛异常
     * @param errorCode
     * @param message
     */
    public static void throwException(String errorCode,String message){
        throw new TxnRuntimeException(errorCode,message);
    }
    /**
     * 抛异常
     * @param jsonObject
     * @return
     */
    public static void jsonThrowException(JSONObject jsonObject){
        throw jsonToException(jsonObject);
    }

    /**
     * 生成异常.
     * @param jsonObject
     * @return
     */
    public static TxnRuntimeException jsonToException(JSONObject jsonObject){
        String errorCode = jsonObject.getStr("errorCode", "500");
        String message = jsonObject.getStr("message", "don't know exception");
        return new TxnRuntimeException(errorCode,message);
    }


    public String getErrorCode() {
        return errorCode;
    }
    public Throwable getThrowable() {
        return throwable;
    }
    @Override
    public String toString() {
        JSONObject jsonObject =new JSONObject();
        jsonObject.set("errorCode",this.errorCode);
        jsonObject.set("message",this.getMessage());
        return jsonObject.toString();
    }
}
